define(['jquery', 'bootstrap', 'utilback', 'table', 'form'], function ($, undefined, Utilback, Table, Form) {

    var Controller = {
    	config: {
    		get_url: '/goods/read/detail',
    	},
        init: function () {
            // 初始化表格参数配置
            Table.api.init({
            	singleSelect: true,
                extend: {
                    index_url: '/goods/read/list',
                    add_url: 'goodsEdit.html',
                    edit_url: 'goodsEdit.html',
                    del_url: '/goods',
                    multi_url: '/goods',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                columns: [
                    [
                        {field: 'state', checkbox: true, },
                        {field: 'id', title: 'ID'},
                        {field: 'goodsName', title: __('商品名称')},
                        {field: 'salePrice', title: __('商品价格')},
                        {field: 'goodsCode', title: __('商品货号')},
                        {field: 'isSale', title: __('商品标签'), formatter: function (value, row, index) {
                        	var html = '';
                  		   html +='<span class="label ' + (row.isSale=='1' ? 'label-info' : 'label-default') + '">上架</span> ';
                 		   html +='<span class="label ' + (row.isPromotion=='1' ? 'label-info' : 'label-default') + '">促销</span> ';
                 		   html +='<span class="label ' + (row.isLimit=='1' ? 'label-info' : 'label-default') + '">限购</span> ';
                     	   return html;
                        }},
                        {field: 'sortNo', title: __('排序')},
                        {field: 'store.storeName', title: __('店铺名称')},
                        {field: 'enable', title: __('审核状态'), formatter: function (value, row, index) {
                        	if(value === '1' || value === 'true') {
        	               		return '<span class="label label-success">审核通过</span>';
        	               	} else if(value === '2') {
        	               		return '<span class="label label-warning">审核拒绝</span>';
        	               	} else {
        	               		return '<span class="label label-info btn btn-deal" data-id="' + row.id + '">未审核</span>';
        	               	}
                        }},
                        {field: 'operate', title: __('Operate'), events: Table.api.events.operate, formatter: function (value, row, index) {
                             return Table.api.formatter.operate.call(this, value, row, index, table);
                        }}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            // 处理事件
            table.on('click', '.btn-deal', function(e) {
                e.stopPropagation();
                var that = this;
                var top = $(that).offset().top - $(window).scrollTop();
                var left = $(that).offset().left - $(window).scrollLeft() - 260;
                if (top + 254 > $(window).height()) {
                    top = top - 254;
                }
                if ($(window).width() < 480) {
                    top = left = undefined;
                }
                var index = Layer.open({
                	content: '审核意见：<textarea id="approveRemark" rows="5" cols="20"></textarea>',
                	offset: [top, left],
                	shadeClose: true,
                	btn: ['通过', '拒绝'],
                    yes: function () {
                    	Util.api.ajax({
                    		type: 'post',
                    		url: '/goods/check',
                    		data: JSON.stringify({id: $(that).attr('data-id') , enable: '1', isSale:'1', remark: $('#approveRemark').text() })
                    	}, function() {
                    		table.bootstrapTable('refresh');
                    	});
                        Layer.close(index);
                    },
                    btn2: function() {
                    	Util.api.ajax({
                    		type: 'post',
                    		url: '/goods/check',
                    		data: JSON.stringify({id: $(that).attr('data-id') , enable: '1', isSale:'1', remark: $('#approveRemark').text() })
                    	}, function() {
                    		table.bootstrapTable('refresh');
                    	});
                        Layer.close(index);
                    }
                });
            });
        },
        edit: function () {
            var attributes = {};
            Form.api.bindevent($("form[role=form]"), function() {
            	$.each(attributes, function(k, v) {
            		$.each(v, function(j, vv) {
            			if($('[data-id="' + k+vv+'"]').length == 0) {
                	    	//$('[name="detailDescription"]').val($('.summernote').summernote('code'));
                			var e = $('[data-id="' + k+vv+'.effectPrice"]').val();
                			var s = $('[data-id="' + k+vv+'.stock"]').val();
                			var f = $('[data-id="' + k+vv+'.attributePicture"]').val();
                			var goodsAttribute = { attributeName:k, attributeValue: vv, effectPrice: e, stock: s, attributePicture: f };
                        	var hidden = '<input type="hidden" data-id="' + k+vv+'" name="attributes" value="'+JSON.stringify(goodsAttribute).replace(/\"/g, '&quot;')+'"/>';
                        	$('form[role=form]').append(hidden);
            			}
            		});
            	});
            	return true;
            });
        	Util.api.initSelectOption({
        		target : '[name="storeId"]',
        		url: '/store/read/list',
        		code: 'id',
        		codeText: 'storeName',
        		param : {},
        		next: {
        			target : '[name="typeIdI"]',
            		url: '/goodsClassify/read/list',
            		code: 'id',
            		codeText: 'classifyName',
            		param : {},
            		next: {
            			target : '[name="brandId"]',
                		url: '/goodsBrand/read/list',
                		code: 'id',
                		codeText: 'brandNameZh',
                		param : {},
                		next: {
                			target : '#goodsType',
                    		url: '/dic/read/list',
                    		param : {type:'GOODSTYPE'},
                    		init: function() {
                    			var id = Util.api.query('id');
                            	if(id) {
                            		Form.api.fill($('form'), Controller.config.get_url, id, function(data) {
                	    				if(data.picture) {
                	    					$('#prev1').html('<img height="30px" src="'+data.picture+'">');
                	    				}
                	    				if(data.imgs) {
                	    					$.each(data.imgs.split(','), function(n, value) {
                	    						$('#prev2').append('<img height="30px" src="'+value+'">');
                	    					});
                	    				}
                	    				if(data.goodsImages) {
                	    					$.each(data.goodsImages.split(','), function(n, value) {
                	    						$('#prev3').append('<img height="30px" src="'+value+'">');
                	    					});
                	    				}
                        				$('[name="storeId"]').selectpicker('val',data.storeId);
                        				$('[name="brandId"]').selectpicker('val',data.brandId);
                        				$('[name="typeIdI"]').selectpicker('val',data.typeIdI);
                	                    $('[name="typeIdIi"]').append('<option value="">--请选择--</option>');
                		    			$.each(data['typeIdIis'], function(n, value) {
                		                    $('[name="typeIdIi"]').append('<option value="' + value.id + '">' + value.classifyName + '</option>');
                	 					});
                		 				$('[name="typeIdIi"]').selectpicker('refresh');
                	                    $('[name="typeIdIii"]').append('<option value="">--请选择--</option>');
                		    			$.each(data['typeIdIiis'], function(n, value) {
                		                    $('[name="typeIdIii"]').append('<option value="' + value.id + '">' + value.classifyName + '</option>');
                	 					});
                		 				$('[name="typeIdIii"]').selectpicker('refresh');
                        				$('[name="typeIdIi"]').selectpicker('val',data.typeIdIi);
                        				$('[name="typeIdIii"]').selectpicker('val',data.typeIdIii);
                	    	    		if(data.attributes) {
                	    	    			$.each(data.attributes, function(i, v) {
                	    	    	    		if(attributes[v.attributeName]) {
                	    	    	        		attributes[v.attributeName].push(v.attributeValue);
                	    	    	    		} else {
                	    	    	        		attributes[v.attributeName] = [v.attributeValue];
                	    	    	    		}
                	    	    			});
                	    	    	    	resetAttributes();
                	    	    			$.each(data.attributes, function(i, v) {
                	    	    				$('[data-id="' + v.attributeName+v.attributeValue + '.effectPrice"]').val(v.effectPrice);
                	    	        			$('[data-id="' + v.attributeName+v.attributeValue + '.stock"]').val(v.stock);
                	    	        			$('[data-id="' + v.attributeName+v.attributeValue + '.attributePicture"]').val(v.attributePicture);
                	    	        			if(v.attributePicture) {
                		    	        			$('#p' + v.attributeName+v.attributeValue+'ButtonContainer span').html('<img height="30px" src="'+v.attributePicture+'">');
                	    	        			}
                	    	    			});
                	    	    		}
                	    				//$('.summernote').summernote('code', data.detailDescription);
                	    	    		if(data.isLimit == '1') {
                	    	    			$('[name="isLimit"].chkY').get(0).checked = true;
                	    	    			$('[name="isLimit"].chkY').parents('span').addClass('checked');
                	    	    			$('[name="isLimit"].chkY').click();
                	    	    		}
                	    	    		if(data.isPromotion == '1') {
                	    	    			$('[name="isPromotion"].chkY').get(0).checked = true;
                	    	    			$('[name="isPromotion"].chkY').parents('span').addClass('checked');
                	    	    			$('[name="isPromotion"].chkY').click();
                	    	    		}
                	    			    // 事件
                	    			    $('[name="typeIdI"]').on('change', function() {
                	    			    	changeClassify($(this).val(), 'typeIdII');
                	    					$('[name="typeIdIII"]').html('');
                	    			    });
                	    			    $('[name="typeIdII"]').on('change', function() {
                	    			    	changeClassify($(this).val(), 'typeIdIII');
                	    			    });
                            		});
                            	} else {
            	    			    // 事件
            	    			    $('[name="typeIdI"]').on('change', function() {
            	    			    	changeClassify($(this).val(), 'typeIdII');
            	    					$('[name="typeIdIII"]').html('');
            	    			    });
            	    			    $('[name="typeIdII"]').on('change', function() {
            	    			    	changeClassify($(this).val(), 'typeIdIII');
            	    			    });
                            	}
                    		}
                		}
            		}
        		}
        	});

        	function changeClassify(parentId, name) {
        		Util.api.ajax({
        	    	type: 'PUT',
        	 		url : '/goodsClassify/read/list',
        	 		data: JSON.stringify({parentId: parentId}),
        		}, function(result) {
	 				$('[name="'+name+'"]').html('');
                    $('[name="'+name+'"]').append('<option value="">--请选择--</option>');
	 				//将获取的数据添加到select选项中
	 				$.each(result.data, function(n, value) {
	 					$('[name="'+name+'"]').append('<option value="' + value.id + '">' + value.classifyName + '</option>');
					});
	 				$('[name="'+name+'"]').selectpicker('refresh');
        	    });
        	}
            $('#goodsType').on('change', function() {
            	if(!$(this).val()) {
            		$('.typeAttribute').hide();
            		return;
            	}
            	Util.api.ajax({
        	    	type: 'PUT',
        	 		url : '/goodsTypeAttribute/read/list',
        	 		data: JSON.stringify({ goodsType: $(this).val() }),
            	},function(result) {
            		result.rows.length == 0 ? ($('#goodsTypeAttribute').html('')) : '';
	 				$.each(result.rows, function(n, obj) {
	 					var t = $('#goodsTypeAttribute');
	 					if($('#A' + obj.id).length == 0) {
		 					var html = '<div id="A'+obj.id+'" class="typeAttribute form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">';
		 					html += '<label class="control-label col-xs-3 col-sm-3 col-md-2 col-lg-2 text-right">' + obj.attributeName + "</label>";
		 					html +='<div class="col-xs-9 col-sm-9 col-md-10 col-lg-10 no-padding">';
		 					if(obj.inputStyle == '2') {
		 						$.each(obj.options.split(','), function(i, n) {
				 					if(obj.isOptional === '1' && n) {
				 						html +='<div class="radio-inline"><label  class="choice-inline">';
				 						html +='<input type="radio" name="'+obj.attributeName+'" value="'+n+'" class="styled"> ' + n + '</label></div>';
				 					} else if(obj.isOptional === '2' && n) {
				 						html +='<div class="checkbox-inline"><label  class="choice-inline">';
				 						html +='<input type="checkbox" name="'+obj.attributeName+'" value="'+n+'" class="styled"> ' + n + '</label></div>';
				 					}
		 						});
		 					} else {
		 						html +='<button class="" data-type="'+obj.attributeName+'">自定义</button';
		 					}
		 					html +='</div></div>';
		 					t.append(html);
	 					} else {
	 						$('.typeAttribute').hide();
	 						$('#A' + obj.id).show();
	 					}
					});
                });
            });
            $(document).on('click', '.typeAttribute .styled', function() {
            	if($(this).is(':checked')) {
            		if(attributes[$(this).attr('name')] && $(this).attr('type') == 'checkbox') {
                		attributes[$(this).attr('name')].push($(this).val());
            		} else {
                		attributes[$(this).attr('name')] = [$(this).val()];
            		}
            	} else if(attributes[$(this).attr('name')]) {
            		var v = $(this).val();
            		var n = $(this).attr('name');
            		$.each(attributes[$(this).attr('name')], function(i, o) {
            			if(v == o) {
            				attributes[n].splice(i, 1);
            			}
            		});
            	}
            	resetAttributes();
            });
            function resetAttributes() {
            	var html = '', as = {};
            	$.each(attributes, function(k, v) {
            		if(v.length > 0) {
                		html += '<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">';
                		html += '<label class="control-label col-xs-3 col-sm-3 col-md-2 col-lg-2 text-right">'+k+'</label>';
                		html += '<div class="form-group col-xs-9 col-sm-9 col-md-10 col-lg-10">';
                		$.each(v, function(j, vv) {
                			if(!as[k + vv]) {
                    			var e = $('[data-id="' + k+vv+'.effectPrice"]').val();
                    			var s = $('[data-id="' + k+vv+'.stock"]').val();
                    			var f = $('[data-id="' + k+vv+'.attributePicture"]').val();
                    			var d = $('#p' + k+vv+'ButtonContainer span').text();
                        		html += '<div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">';
                        		html += '<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><input type="input" class="form-control" readonly="radonly" value="' + vv + '"/></div>';
                        		html += '<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><input type="input" class="form-control" data-id="'+k+vv+'.effectPrice" placeholder="价格影响" value="'+(e ? e : '0')+'" data-rule="required" /></div>';
                        		html += '<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><input type="input" class="form-control" data-id="'+k+vv+'.stock" placeholder="库存" value="'+(s ? s : '')+'" data-rule="required"/></div>';
                        		html += '<input type="hidden" name="'+k+vv+'.attributePicture" value="'+(f ? f : '')+'"/><span id="p'+k+vv+'ButtonContainer">'
                			        +'<a class="btn bg-teal add-btn" id="p'+k+vv+'Button" href="javascript:void(0);">上传图片</a>'
                			        +'<span>'+(d?d:'')+'</span></span>';
                        		html += '</div>';
                        		as[k + vv] = "1";
                			}
                		});
                		html += '</div></div>';
            		}
            	});
            	$('#goodsAttribute').html(html);
            	$.each(attributes, function(k, v) {
            		$.each(v, function(j, vv) {
            			$(document).trigger('initUploader', { button: 'p'+k+vv+'Button', target: k+vv+'.attributePicture'});
            		});
            	});
            }
            $('.chkN').on('click', function() {
            	//$('#' + $(this).attr('data-biz-target')).hide();
            	$('#' + $(this).attr('data-biz-target') + ' input').attr('disabled', 'disabled');
            });
            $('.chkY').on('click', function() {
            	//$('#' + $(this).attr('data-biz-target')).show();
            	$('#' + $(this).attr('data-biz-target') + ' input').removeAttr('disabled');
            });
        }
    };
    return Controller;
});